//
//  ViewController.m
//  VolumeControl
//
//  Created by yao zhaofeng on 2018/8/27.
//  Copyright © 2018年 YaoZhaofeng. All rights reserved.
//
//代码设置手机音量大小，通过创建MPVolumeView，然后从其子view中获取类描述为MPVolumeSlider的子view，来设置音量的大小
//如果MPVolumeView隐藏，则会在手机中间展示音量调节的提示，如果不想要该提示，可以将MPVolumeView添加到屏幕外面进行展示。

#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property (nonatomic, strong) MPVolumeView *volumeView;
@property (nonatomic, strong) AVAudioPlayer *player;
@end

@implementation ViewController
- (IBAction)BtnClick:(id)sender {
}
- (IBAction)ButtonClick:(id)sender {
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self playBackgroundMusic];
    // Dispose of any resources that can be recreated.
    UISlider *volumeSlider = [[UISlider alloc] init];
    volumeSlider.frame = CGRectMake(50, 100, self.view.frame.size.width - 100, 40);
    [volumeSlider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    //    [volumeSlider addTarget:self action:@selector(touchupOutside:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:volumeSlider];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)playBackgroundMusic {
    NSString *path = [[NSBundle mainBundle]pathForResource:@"opening" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.player = player;
    player.numberOfLoops = -1;
    player.volume = 0.5f;
    [player prepareToPlay];
    [player play];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)valueChanged:(UISlider *)sender {
    [self setVolume:sender.value];
}


/*
 * 设置音量
 */
- (void)setVolume:(float)value {
    
    UISlider *volumeSlider = [self volumeSlider];
    self.volumeView.showsVolumeSlider = YES; // 需要设置 showsVolumeSlider 为 YES
    // 下面两句代码是关键
    [volumeSlider setValue:value animated:NO];
    [volumeSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
    [self.volumeView sizeToFit];
}

- (MPVolumeView *)volumeView {
    if (!_volumeView) {
        _volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(0, -100, 10, 10)];
        [[UIApplication sharedApplication].keyWindow addSubview:_volumeView];
    }
    return _volumeView;
}
/*
 * 遍历控件，拿到UISlider
 */
- (UISlider *)volumeSlider {
    UISlider* volumeSlider = nil;
    for (UIView *view in [self.volumeView subviews]) {
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            volumeSlider = (UISlider *)view;
            break;
        }
    }
    return volumeSlider;
}
@end
